package com.qinge.blog.utils.aspect;

import com.baomidou.mybatisplus.annotation.TableField;
import com.qinge.blog.utils.UUIDUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author QDW
 * @date 2022/5/10 17:21
 * @description
 **/
@Aspect
@Order(2)  // 该切面应当先于 @Transactional 执行
@Component
public class AutoFillAspect {

    @Pointcut("execution(public  * com.qinge.blog.service.impl..*.add(..))")
    public void add() {
    }

    @Pointcut("execution(public  * com.qinge.blog.service.impl..*.addByList(..))")
    public void addByList() {
    }

    @Pointcut("execution(public  * com.qinge.blog.service.impl..*.update(..))")
    public void update(){

    }

    @Pointcut("execution(public  * com.qinge.blog.service.impl..*.upsert(..))")
    public void upsert(){

    }

    /**
     * 切换数据源
     */
    @Before(value = "add()")
    public void addBefore(JoinPoint joinPoint) throws Throwable {
        Object obj = joinPoint.getArgs()[0];
        autoFillByAdd(obj);
    }

    /**
     * 切换数据源
     */
    @Before("addByList()")
    public void addByListBefore(JoinPoint joinPoint) throws Throwable {
        // 获取切入的 Method
        Object obj = joinPoint.getArgs()[0];
        autoFillByUpdate(obj);
    }

    /**
     * @author QDW
     * @date 2022/5/10 19:42
     * @description 填充upsert方法的数据
     * @param joinPoint
     * @return void
     **/
    @Before("update()")
    public void updateBefore(JoinPoint joinPoint) throws Throwable {
        // 获取切入的 Method
        Object obj = joinPoint.getArgs()[0];
        autoFillByUpdate(obj);
    }


    /**
     * @author QDW
     * @date 2022/5/10 19:42
     * @description 填充upsert方法的数据
     * @param joinPoint
     * @return void
     **/
    @Before("upsert()")
    public void upsertBefore(JoinPoint joinPoint) throws Throwable {
        // 获取切入的 Method
        Object obj = joinPoint.getArgs()[0];
        autoFillByUpsert(obj);
    }

    /**
     * @author QDW
     * @date 2022/5/10 18:54
     * @description 添加的时候填充
     * @param obj
     * @return void
     **/
    private static void autoFillByAdd(Object obj) throws IllegalAccessException, InstantiationException {
        // 布尔值填充
        String[] booleanArr=new String[]{"enabled","accountNonExpired","accountNonLocked","credentialsNonExpired"};
        List<String> booleanList= Arrays.asList(booleanArr);

        // 时间填充
        String[] dateArr=new String[]{"createTime","updateTime","lastLoginTime"};
        List<String> dateList=Arrays.asList(dateArr);

        addBooleanAndDate(obj,booleanList,dateList);
    }

    /**
     * @author QDW
     * @date 2022/5/10 18:54
     * @description 更新的时候填充，目前只填充3种类型 String,Date,Boolean
     * @param obj
     * @return void
     **/
    private static void autoFillByUpdate(Object obj) throws IllegalAccessException, InstantiationException {
        // 布尔值填充
        String[] booleanArr=new String[]{"enabled","accountNonExpired","accountNonLocked","credentialsNonExpired"};
        List<String> booleanList= Arrays.asList(booleanArr);

        // 时间填充
        String[] dateArr=new String[]{"updateTime","lastLoginTime"};
        List<String> dateList=Arrays.asList(dateArr);

        addBooleanAndDate(obj,booleanList,dateList);
    }

    /**
     * @author QDW
     * @date 2022/5/10 19:42
     * @description
     * @param obj
     * @return void
     **/
    private static void autoFillByUpsert(Object obj) throws IllegalAccessException, InstantiationException {
        // 布尔值填充
        String[] booleanArr=new String[]{};
        List<String> booleanList= Arrays.asList(booleanArr);

        // 时间填充
        String[] dateArr=new String[]{"updateTime","lastLoginTime"};
        List<String> dateList=Arrays.asList(dateArr);

        addBooleanAndDate(obj,booleanList,dateList);
    }


    /**
     * @author QDW
     * @date 2022/5/10 18:53
     * @description 填充布尔值和日期
     * @param obj
     * @param booleanList
     * @param dateList
     * @return void
     **/
    public static void addBooleanAndDate(Object obj,List<String> booleanList,List<String> dateList) throws IllegalAccessException, InstantiationException {
        Object[] objArr=null;

        if(obj.getClass().isArray()){
            int length = Array.getLength(obj);
            objArr = new Object[length];
            for (int i = 0; i < objArr.length; i++) {
                objArr[i] = Array.get(obj, i);
            }
        }else{
            objArr=new Object[1];
            objArr[0]=obj;
        }

        if(objArr!=null){
            for(Object each:objArr){
                // Field[] fields = each.getClass().getDeclaredFields();


                List<Field> fields = new ArrayList<>() ;;
                fields.addAll(Arrays.asList(each.getClass().getDeclaredFields()));

                // 只对实体进行填充 获取一次父类的字段
                if(each.getClass().getSuperclass()!=null){
                    fields.addAll(Arrays.asList(each.getClass().getSuperclass().getDeclaredFields()));
                }

                for (Field field : fields) {
                    field.setAccessible(true);
                    String fileName = field.getName();

                    // 自动填充字符类型 null填充为空字符串
                    if(field.getType().equals(String.class)){
                        String value = (String) field.get(each);
                        if(value==null){
                            // id 为空自动生成
                            if("id".equals(fileName)){
                                field.set(each, UUIDUtil.getUUID32());
                            }else{
                                field.set(each, "");
                            }
                        }
                    }

                    // 对应属性 创建值
                    if(booleanList.contains(fileName)){
                        field.set(each, true);
                    }

                    // 填充时间
                    if(dateList.contains(fileName)){
                        field.set(each,new Date());
                    }

                }
            }
        }

    }


}
